package others;

import lombok.SneakyThrows;
import ui.common.CommonPanel;
import ui.label.LimpidLabel;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;

public class RectDraw extends CommonPanel {

    private static final long serialVersionUID = 1L;
    public int orgx, orgy, endx, endy;

    public RectDraw(){}

    public RectDraw(int x, int y, int width, int height, String path) {
        JLabel viewLabel = new LimpidLabel(new ImageIcon(path),0, 0, 300, 300);
        viewLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
        this.add(viewLabel);
        this.setBounds(x,y,width,height);
        this.setVisible(true);
        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                orgx = e.getX();
                orgy = e.getY();
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @SneakyThrows
            public void mouseDragged(MouseEvent e) {
                endx = e.getX();
                endy = e.getY();
                Graphics g = getGraphics();
                BufferedImage bg = ImageIO.read(new File(path));
                g.drawImage(bg.getScaledInstance(300, 300, Image.SCALE_DEFAULT), 1, 0, null);
                g.setColor(Color.RED);
                g.drawRect(orgx, orgy, endx - orgx, endy - orgy);
            }
        });
    }
}

